import React, { Component, useState } from 'react'

export default class CountTimeDown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      day: 0,
      hour: 0,
      minute: 0,
      second: 0
    }
  }

  componentDidMount() {
    if (this.props.endTime) {
      let endTime = this.props.endTime.replace(/-/g, "/");
      this.countFun(endTime);
    }
  }

  componentDidUpdate(){
    // console.log('.......')
  }

  //组件卸载取消倒计时
  componentWillUnmount() {
    clearInterval(this.timer);
  }



  countFun = (time) => {
    let end_time = new Date(time).getTime()
    let sys_second = (end_time - new Date().getTime())
    this.timer = setInterval(() => {
      //防止倒计时出现负数
      if (sys_second > 1000) {
        sys_second -= 1000;
        let day = Math.floor((sys_second / 1000 / 3600) / 24);
        let hour = Math.floor((sys_second / 1000 / 3600) % 24);
        let minute = Math.floor((sys_second / 1000 / 60) % 60);
        let second = Math.floor(sys_second / 1000 % 60);
        this.setState({
          day: day,
          hour: hour < 10 ? "0" + hour : hour,
          minute: minute < 10 ? "0" + minute : minute,
          second: second < 10 ? "0" + second : second
        })
      } else {
        clearInterval(this.timer);
        this.props.overCall && this.props.overCall();
      }
    }, 1000);
  };

  render() {
    return (
      <span>
        {this.state.day ? `${this.state.day}天`:''}
        {this.state.hour}时{this.state.minute}分{this.state.second}秒
      </span>
    )
  }
}

// var CountTimeDown = (props)=>{
//     console.log(props);
//     let endTime = props.endTime.replace(/-/g, "/");
//     let timer=null;
//     const [timeInfo,setTimeInfo] = useState({day: 0,hour: 0,minute: 0,second: 0})
//     let countFun = (time) => {
//       let end_time = new Date(time).getTime(),
//       sys_second = (end_time - new Date().getTime());
//       timer = setInterval(() => {
//         //防止倒计时出现负数
//         if (sys_second > 1000) {
//           sys_second -= 1000;
//           let day = Math.floor((sys_second / 1000 / 3600) / 24);
//           let hour = Math.floor((sys_second / 1000 / 3600) % 24);
//           let minute = Math.floor((sys_second / 1000 / 60) % 60);
//           let second = Math.floor(sys_second / 1000 % 60);
//           setTimeInfo({
//               day: day,
//               hour: hour < 10 ? "0" + hour : hour,
//               minute: minute < 10 ? "0" + minute : minute,
//               second: second < 10 ? "0" + second : second
//             })
//         } else {
//           clearInterval(timer);
//           props.overCall && props.overCall();
//         }
//       }, 1000);
//     };
//     countFun(endTime);
//     return (
//       <span>
//         { timeInfo.day && `${timeInfo.day}天`
//         `${timeInfo.hour}时${timeInfo.minute}分${timeInfo.second}秒` }
//       </span>
//     ) 
// }

// export default CountTimeDown